package org.jctc.els.modules.biz.service.proTemplate.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.checkerframework.checker.units.qual.A;
import org.jctc.els.modules.biz.entity.pro.ElsProjectReview;
import org.jctc.els.modules.biz.entity.pro.ProjectReviewDetailed;
import org.jctc.els.modules.biz.entity.pro.ProjectReviewOptions;
import org.jctc.els.modules.biz.entity.proTemplate.*;
import org.jctc.els.modules.biz.mapper.proTemplate.ProjectReviewTemplateDetailedMapper;
import org.jctc.els.modules.biz.mapper.proTemplate.ProjectReviewTemplateMapper;
import org.jctc.els.modules.biz.mapper.proTemplate.ProjectReviewTemplateOptionsMapper;
import org.jctc.els.modules.biz.service.proTemplate.ProjectReviewTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Arrays;
import java.util.List;

/**
 * 评审模板表;(els_project_review_template)表服务实现类
 * @author : http://www.chiner.pro
 * @date : 2022-6-21
 */
@Service
public class ProjectReviewTemplateServiceImpl implements ProjectReviewTemplateService {
    @Autowired
    private ProjectReviewTemplateMapper projectReviewTemplateMapper;
    @Autowired
    private ProjectReviewTemplateDetailedMapper projectReviewTemplateDetailedMapper;
    @Autowired
    private ProjectReviewTemplateOptionsMapper projectReviewTemplateOptionsMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public ProjectReviewTemplate queryById(Long id){
        return projectReviewTemplateMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @param projectReviewTemplate 筛选条件
     * @param current 当前页码
     * @param size  每页大小
     * @return
     */
    public Page<ProjectReviewTemplate> paginQuery(ProjectReviewTemplate projectReviewTemplate, long current, long size){
        //1. 构建动态查询条件
        LambdaQueryWrapper<ProjectReviewTemplate> queryWrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotBlank(projectReviewTemplate.getName())){
            queryWrapper.eq(ProjectReviewTemplate::getName, projectReviewTemplate.getName());
        }
        if(StrUtil.isNotBlank(projectReviewTemplate.getReviewResult())){
            queryWrapper.eq(ProjectReviewTemplate::getReviewResult, projectReviewTemplate.getReviewResult());
        }
        if(StrUtil.isNotBlank(projectReviewTemplate.getRemark())){
            queryWrapper.eq(ProjectReviewTemplate::getRemark, projectReviewTemplate.getRemark());
        }
        //2. 执行分页查询
        Page<ProjectReviewTemplate> pagin = new Page<>(current , size , true);
        IPage<ProjectReviewTemplate> selectResult = projectReviewTemplateMapper.selectByPage(pagin , queryWrapper);
        pagin.setPages(selectResult.getPages());
        pagin.setTotal(selectResult.getTotal());
        pagin.setRecords(selectResult.getRecords());
        //3. 返回结果
        return pagin;
    }

    /**
     * 新增数据
     *
     * @param projectReviewTemplate 实例对象
     * @return 实例对象
     */
    public ProjectReviewTemplate insert(ProjectReviewTemplate projectReviewTemplate){
        projectReviewTemplateMapper.insert(projectReviewTemplate);
        return projectReviewTemplate;
    }

    /**
     * 更新数据
     *
     * @param projectReviewTemplate 实例对象
     * @return 实例对象
     */
    public ProjectReviewTemplate update(ProjectReviewTemplate projectReviewTemplate){
        //1. 根据条件动态更新
        LambdaUpdateChainWrapper<ProjectReviewTemplate> chainWrapper = new LambdaUpdateChainWrapper<ProjectReviewTemplate>(projectReviewTemplateMapper);
        if(StrUtil.isNotBlank(projectReviewTemplate.getName())){
            chainWrapper.eq(ProjectReviewTemplate::getName, projectReviewTemplate.getName());
        }
        if(StrUtil.isNotBlank(projectReviewTemplate.getReviewResult())){
            chainWrapper.eq(ProjectReviewTemplate::getReviewResult, projectReviewTemplate.getReviewResult());
        }
        if(StrUtil.isNotBlank(projectReviewTemplate.getRemark())){
            chainWrapper.eq(ProjectReviewTemplate::getRemark, projectReviewTemplate.getRemark());
        }
        //2. 设置主键，并更新
        chainWrapper.set(ProjectReviewTemplate::getId, projectReviewTemplate.getId());
        boolean ret = chainWrapper.update();
        //3. 更新成功了，查询最最对象返回
        if(ret){
            return queryById(projectReviewTemplate.getId());
        }else{
            return projectReviewTemplate;
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public boolean deleteById(Long id){
        Boolean result = false;
        //删除选项
        List<ProjectReviewTemplateOptions> optionsList = projectReviewTemplateOptionsMapper.selectList(new QueryWrapper<ProjectReviewTemplateOptions>().eq("project_review_id", id));
        if (optionsList.size() > 0) {
            ProjectReviewTemplateOptions options = new ProjectReviewTemplateOptions();
            options.setIsDeleted(1);
            result = projectReviewTemplateOptionsMapper.update(options,new QueryWrapper<ProjectReviewTemplateOptions>().eq("project_review_id",id)) > 0;
            if (BooleanUtil.isFalse(result)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        List<ProjectReviewTemplateDetailed> detailedList = projectReviewTemplateDetailedMapper.selectList(new QueryWrapper<ProjectReviewTemplateDetailed>().eq("project_review_id", id));
        if (detailedList.size() > 0) {
            //删除维度表
            ProjectReviewTemplateDetailed detailed = new ProjectReviewTemplateDetailed();
            detailed.setIsDeleted(1);
            result = projectReviewTemplateDetailedMapper.update(detailed,new QueryWrapper<ProjectReviewTemplateDetailed>().eq("project_review_id",id))>0;
            if (BooleanUtil.isFalse(result)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        ProjectReviewTemplate projectReview = new ProjectReviewTemplate();
        projectReview.setIsDeleted(1);
        projectReview.setId(id);
        result = projectReviewTemplateMapper.updateById(projectReview) > 0;
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    @Override
    public ProjectReviewTemplateVO selectByCategory(Integer projectReviewCategory) {
        ProjectReviewTemplateVO vo = new ProjectReviewTemplateVO();
        //获取模板基本信息
        ProjectReviewTemplate projectReviewTemplate = projectReviewTemplateMapper.selectOne(new QueryWrapper<ProjectReviewTemplate>().eq("project_review_category", projectReviewCategory));
        vo.setBasic(projectReviewTemplate);
        //获取一级维度
        List<ProjectReviewTemplateDetailedVO> oneLevelList = projectReviewTemplateDetailedMapper.selectLowerLevelList(projectReviewTemplate.getId(),0L,1);
        //获取下级维度
        oneLevelList = selectLowerLevel(oneLevelList,projectReviewTemplate.getId());
        vo.setOneLevel(oneLevelList);
        return vo;
    }

    public List<ProjectReviewTemplateDetailedVO> selectLowerLevel(List<ProjectReviewTemplateDetailedVO> levelList,Long projectReviewId) {
        for (ProjectReviewTemplateDetailedVO vo : levelList) {
            List<ProjectReviewTemplateDetailedVO> twoLevelList = projectReviewTemplateDetailedMapper.selectLowerLevelList(projectReviewId,vo.getId(),vo.getLevel() + 1);
            if (twoLevelList.size() == 0) {
                //没有下级维度 查询选项
                String[] optionIdList = vo.getOptionIds().split(",");
                List<ProjectReviewTemplateOptions> optionsList = projectReviewTemplateOptionsMapper.selectList(new QueryWrapper<ProjectReviewTemplateOptions>().in("id",optionIdList));
                vo.setOptionList(optionsList);
                vo.setLowerLevelNum(0);
                continue;
            }
            vo.setLowerLevel(twoLevelList);
            vo.setLowerLevelNum(twoLevelList.size());
            selectLowerLevel(twoLevelList,projectReviewId);
        }
        return levelList;
    }

    @Override
    public ProjectReviewTemplateVO selectByProjectReviewId(Long projectReviewId) {
        ProjectReviewTemplateVO vo = new ProjectReviewTemplateVO();
        //获取模板基本信息
        ProjectReviewTemplate projectReviewTemplate = projectReviewTemplateMapper.selectOne(new QueryWrapper<ProjectReviewTemplate>().eq("id", projectReviewId));
        vo.setBasic(projectReviewTemplate);
        //获取最大的维度等级
//        Integer maxLevel = projectReviewTemplateDetailedMapper.selectMaxLevel(projectReviewId);
        //获取一级维度
        List<ProjectReviewTemplateDetailedVO> oneLevelList = projectReviewTemplateDetailedMapper.selectLowerLevelList(projectReviewTemplate.getId(),0L,1);
        //获取下级维度
        oneLevelList = selectLowerLevel(oneLevelList,projectReviewId);
        vo.setOneLevel(oneLevelList);
        return vo;
    }



    @Override
    public Page<ProjectReviewTemplate> selectPageList(Integer pageNum, Integer pageSize,String name) {
        Page<ProjectReviewTemplate> pagin = new Page<>(pageNum,pageSize);
        return projectReviewTemplateMapper.selectPageList(pagin,name);
    }

    @Override
    public List<ProjectReviewTemplate> selectList() {
        return projectReviewTemplateMapper.selectLists();
    }
}
